package com.wang.common.interceptor;

import com.wang.common.common.ErrorCode;
import com.wang.common.exception.BusinessException;
import com.wang.common.model.RUser;
import com.wang.common.utils.RedisUtil;
import com.wang.common.utils.TokenUtil;
import com.wang.common.utils.Utils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录检查
 * 1、配置好拦截器要拦截哪些请求
 * 2、把这些配置放在容器中
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 目标方法执行之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String token = request.getHeader("token");
//        if (Utils.isEmpty(token)) throw new BusinessException(ErrorCode.NO_LOGIN);
//        RUser rUser = (RUser) Utils.jsonStringToObj(redisUtil.getString(token), RUser.class);
//        if (Utils.isEmpty(rUser)) throw new BusinessException(ErrorCode.NO_LOGIN);
//        boolean verify = TokenUtil.verify(token);
//        if (verify) return true;
//        // 删除缓存
//        redisUtil.deleteString(token);
//        throw new BusinessException(ErrorCode.LOGIN_TIMEOUT, "登录超时，请重新登录");
        return true;
    }

    /**
     * 目标方法执行之后
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 页面渲染之后
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
